home *** CD-ROM | disk | FTP | other *** search
- Path: amaryllisp1.appsig.com!user
- From: larry_kearney@appsig.com (Lawrence Kearney)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Fri, 19 Jan 1996 13:35:26 -0700
- Organization: Applied Signal Technology
- Message-ID: <larry_kearney-1901961335260001@amaryllisp1.appsig.com>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: amaryllisp1.appsig.com
-
- > Is there a fast way to decide whether a number n is a power of 2?
- >...
- > Since I am dealing with unsigned long ints, I guess I can just store all
- > 31 powers of 2 in a table and compare to n. Though I don't know a fast
- > algorithm to compare a number to 31 numbers in an array.
- > Thanks very much for any help.
- >
- > Bill Simpson
-
- I think that if you use a table lookup using a binary search algorithm,the
- maximum number of comparisons that you would have to make would be either
- 5 or 6 as a worst case. This would have to be considerably faster that
- performing a floating point log and divide.
-
- To eliminate odd numbers, you might first want to test to see if the
- number is odd or even by looking at the LSB. If the bit is 0, then procede
- to the table lookup. If the bit is set, it obviously can't be an even
- power of two.
-
- --
- Larry Kearney | "You want fries with that?"
- Applied Signal Technology |
- larry_kearney@appsig.com |
-